def build_kmp_table(pattern):
    """
    构建KMP算法的部分匹配表
    """
    table = [0] * len(pattern)
    i = 0
    j = 1

    while j < len(pattern):
        if pattern[i] == pattern[j]:
            i += 1
            table[j] = i
            j += 1
        else:
            if i != 0:
                i = table[i - 1]
            else:
                table[j] = 0
                j += 1

    return table

def kmp_search(text, pattern):
    """
    使用KMP算法在文本中查找模式串，并返回匹配的起始位置列表
    """
    table = build_kmp_table(pattern)
    i = 0
    j = 0
    matches = []

    while i < len(text):
        if pattern[j] == text[i]:
            i += 1
            j += 1

            if j == len(pattern):
                matches.append(i - j)
                j = table[j - 1]
        else:
            if j != 0:
                j = table[j - 1]
            else:
                i += 1

    return matches